﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using ETL.Common.Logging;
using ETL.Entity;
using ETL.Common;

namespace ETL.DataAccess
{
    public class ProjectTimeRepository
    {
        /// <summary>
        /// Get latest record from project_times
        /// return null if cannot find lastest item
        /// </summary>
        /**public project_times GetLastProjectTime(string userId)
        {
            try
            {
                var db = new ETLDataEntities();
                
                var lastestProjectTime = (from s in db.project_times
                                          where s.time_project > 0 && s.time_category > 0 && s.time_task_id > 0 && s.time_user_id == userId orderby s.time_ref descending 
                                          select s).FirstOrDefault();

                if (lastestProjectTime != null)
                {
                    var projectId = lastestProjectTime.time_project;
                    var categoryId = lastestProjectTime.time_category;
                    var taskid = lastestProjectTime.time_task_id;

                    var lastestTime = (from t in db.project_times
                                       where t.time_project == projectId && t.time_category == categoryId && t.time_task_id == taskid
                                       select t).FirstOrDefault();
                    if (lastestTime != null)
                    {
                        return lastestTime;
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return null;
            }
        }**/

        public ETL_ACTUAL_RESOURCE_USAGES GetLastProjectTime(string userId)
        {
            try
            {
                var db = new ETLDataEntities();

                var lastestProjectTime = (from s in db.ETL_ACTUAL_RESOURCE_USAGES
                                          join r in db.RESOURCE_INSTANCES on s.GEN_RESOURCE_ID equals r.GEN_RESOURCE_ID
                                          where s.GEN_TASK_ID > 0 && r.RESOURCE_NAME == userId
                                          orderby s.GEN_ACTUAL_RESOURCE_USAGE_ID descending
                                          select s).FirstOrDefault();

                if (lastestProjectTime != null)
                {
                    //var projectId = lastestProjectTime.time_project;
                    //var categoryId = lastestProjectTime.time_category;
                    var taskid = lastestProjectTime.GEN_TASK_ID;

                    var lastestTime = (from t in db.ETL_ACTUAL_RESOURCE_USAGES
                                       where t.GEN_TASK_ID == taskid
                                       select t).FirstOrDefault();
                    if (lastestTime != null)
                    {
                        return lastestTime;
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return null;
            }
        }

        /**public IEnumerable<project_times> GetAllProjectTimes(string userId, DateTime beforeDate)
        {
            try
            {
                var db = new ETLDataEntities();

                var allPrjTimes = from s in db.project_times
                                  where s.time_start > beforeDate && s.time_user_id == userId
                                   orderby s.time_start
                                   select s;

                if (allPrjTimes != null)
                {
                    return allPrjTimes;
                }

                return null;
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return null;
            }
        }**/

    
        public IEnumerable<ETL_ACTUAL_RESOURCE_USAGES> GetAllProjectTimes(string userId, DateTime beforeDate)
        {
            try
            {
                var db = new ETLDataEntities();

                var allPrjTimes = from s in db.ETL_ACTUAL_RESOURCE_USAGES
                                  join r in db.RESOURCE_INSTANCES on s.GEN_RESOURCE_ID equals r.GEN_RESOURCE_ID
                                  where s.GEN_TASK_ID > 0 && r.RESOURCE_NAME == userId
                                  where s.START_DATE > beforeDate && r.RESOURCE_NAME == userId
                                   orderby s.START_DATE
                                   select s;

                if (allPrjTimes != null)
                {
                    return allPrjTimes;
                }

                return null;
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return null;
            }
        }

        /// <summary>
        /// Get latest record from project_times
        /// return null if cannot find lastest item
        /// </summary>
        /**public project_times GetLatestProjectTimes()
        {
            try
            {
                var db = new ETLDataEntities();
                var currentTimeRefList = (from emp in db.project_times select emp.time_ref);

                if (currentTimeRefList.Count() > 0)
                {
                    int currentTimeRef = currentTimeRefList.Max();
                    var prjTimes = (from emp in db.project_times where emp.time_ref == currentTimeRef select emp).FirstOrDefault();

                    if (prjTimes != null)
                    {
                        return prjTimes;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }

            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return null;
            }
        }**/


        public ETL_ACTUAL_RESOURCE_USAGES GetLatestProjectTimes()
        {
            try
            {
                var db = new ETLDataEntities();
                var currentTimeRefList = (from emp in db.ETL_ACTUAL_RESOURCE_USAGES select emp.GEN_ACTUAL_RESOURCE_USAGE_ID);

                if (currentTimeRefList.Count() > 0)
                {
                    int currentTimeRef = (int)currentTimeRefList.Max();
                    var prjTimes = (from emp in db.ETL_ACTUAL_RESOURCE_USAGES where emp.GEN_ACTUAL_RESOURCE_USAGE_ID == currentTimeRef select emp).FirstOrDefault();

                    if (prjTimes != null)
                    {
                        return prjTimes;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }

            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return null;
            }
        }



        /// <summary>
        /// Create latest record of project_times
        /// </summary>
        /**public void CreateNewProjectTimes(short? p, short? c, short? t, string username, string userid)
        {
            try
            {
                var db = new ETLDataEntities();
                var current = GetLatestProjectTimes();
                var time = new project_times
                {
                    time_ref = ++current.time_ref,
                    time_task_id = t,
                    time_project = p,
                    time_category = c,
                    time_user_id = userid,
                    time_start = DateTime.Now,
                    time_name = username,
                    time_other = null,
                    time_finish = null,
                    time_hours = null
                };

                db.project_times.Add(time);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
            }

        }**/

        public void CreateNewProjectTimes(short? p, short? c, short? t, string username, string userid)
        {
            try
            {
                var db = new ETLDataEntities();
                var current = GetLatestProjectTimes();

                ProjectResourceRepository _projectResourceRepository = new ProjectResourceRepository();

                // try to get from db
                RESOURCE_INSTANCES prjActualResourceItem =
                    _projectResourceRepository.GetResourceByName(userid);

                var time = new ETL_ACTUAL_RESOURCE_USAGES
                {
                    GEN_TASK_ID = t,
                    GEN_RESOURCE_ID = prjActualResourceItem.RESOURCE_ID,
                    START_DATE = DateTime.Now,
                    END_DATE = null
                };

                db.ETL_ACTUAL_RESOURCE_USAGES.Add(time);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
            }

        }





        /// <summary>
        /// Create latest record of project_times
        /// </summary>
        /**public void CreateNewProjectTimes(short? p, short? c, short? t, string username, string userid, DateTime dt, float hours)
        {
            try
            {
                var db = new ETLDataEntities();
                var current = GetLatestProjectTimes();
                var time = new project_times
                {
                    time_ref = ++current.time_ref,
                    time_task_id = t,
                    time_project = p,
                    time_category = c,
                    time_user_id = userid,
                    time_name = username,
                    time_other = null, //cboverhead
                    time_hours = hours,
                    time_notes = "Free entry",
                    time_start = dt,
                    time_finish = dt,
                
                };

                db.project_times.Add(time);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
            }

        }**/

        public void CreateNewProjectTimes(short? p, short? c, short? t, string username, string userid, DateTime dt, float hours)
        {
            try
            {
                var db = new ETLDataEntities();
                var current = GetLatestProjectTimes();

                ProjectResourceRepository _projectResourceRepository = new ProjectResourceRepository();

                // try to get from db
                RESOURCE_INSTANCES prjActualResourceItem =
                    _projectResourceRepository.GetResourceByName(userid);

                var time = new ETL_ACTUAL_RESOURCE_USAGES
                {
                    GEN_TASK_ID = t,
                    GEN_RESOURCE_ID = prjActualResourceItem.RESOURCE_ID,
                    START_DATE = DateTime.Now,
                    END_DATE = DateTime.Now
                };

                db.ETL_ACTUAL_RESOURCE_USAGES.Add(time);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
            }

        }



        //Update DB when user click on "Other Activity"
        /**public void CreateNewProjectTimes(short? p, short? c, string username, string userid, string timeOther,string timeReason)
        {
            try
            {
                var db = new ETLDataEntities();
                var current = GetLatestProjectTimes();
                var time = new project_times
                {
                    time_ref = ++current.time_ref,
                    time_task_id = null,
                    time_project = p,
                    time_category = c,
                    time_user_id = userid,
                    time_start = DateTime.Now,
                    time_name = username,
                    time_other = timeOther,
                    time_finish = null,
                    time_hours = null,
                    time_reason = timeReason
                };

                db.project_times.Add(time);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
            }

        }**/


        //Update DB when user click on "Other Activity"
        public void CreateNewProjectTimes(short? p, short? c, string username, string userid, string timeOther, string timeReason)
        {
            try
            {
                var db = new ETLDataEntities();
                var current = GetLatestProjectTimes();
                ProjectResourceRepository _projectResourceRepository = new ProjectResourceRepository();

                // try to get from db
                RESOURCE_INSTANCES prjActualResourceItem =
                    _projectResourceRepository.GetResourceByName(userid);

                var time = new ETL_ACTUAL_RESOURCE_USAGES
                {
                    //GEN_TASK_ID = t,     //category not deprecated so need each other activity (category) to have be assigned a trask
                    GEN_RESOURCE_ID = prjActualResourceItem.RESOURCE_ID,
                    START_DATE = DateTime.Now,
                    END_DATE = DateTime.Now
                };

                db.ETL_ACTUAL_RESOURCE_USAGES.Add(time);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
            }

        }


        
        public bool ClockOff(string userid, string username)
        {
            /**
            try
            {
                var db = new ETLDataEntities();
                bool modified = false;
                DateTime startTime;

                int timediff;

                float hours = 0;

                // select records of this user in project_times
                IEnumerable<project_times> lstPrjTime = from s in db.project_times
                                 where
                                     s.time_user_id.Equals(userid) && s.time_notes == null && s.time_finish == null
                                 orderby s.time_start descending
                                 select s;

                if (lstPrjTime != null && lstPrjTime.Count() > 0)
                {
                    var r = lstPrjTime.First();
                    if(r!=null)
                    {
                        if(r.time_finish == null)
                        {
                            if (r.time_start.HasValue)
                            {
                                var dt = r.time_start.Value;
                                timediff = DateTime.Compare(DateTime.Now, dt);
                                modified = false;
                                if(timediff < 0)
                                {
                                    modified = true;
                                    hours = 0;
                                }
                                else
                                {
                                    TimeSpan ts1 = DateTime.Now.Subtract(dt);
                                    hours = Convert.ToSingle(ts1.TotalHours);

                                    if (hours < 0)
                                        hours = 0;

                                    hours *= 100;
                                    hours = Convert.ToInt32(hours);
                                    hours /= 100;
                                }
                            }

                        }
                    }

                }
                db.Dispose();
                db = new ETLDataEntities();
                var lstAll = from s in db.project_times where s.time_name == username && s.time_finish == null select s;
                if(lstAll != null && lstAll.Count() > 0)
                {
                    List<project_times> list = lstAll.ToList();

                    foreach (project_times item in list)
                    {
                        if(modified)
                        {
                            item.time_hours = hours;
                            item.time_start = DateTime.Now;
                            item.time_finish = DateTime.Now;

                        }
                        else
                        {
                            item.time_hours = hours;
                            item.time_finish = DateTime.Now;
                        }

                        db.Entry(item).State = EntityState.Modified;
                        int i = db.SaveChanges();
                        if (i > 0) return true;
                    }
                }

                return false;
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return false;
            }
             **/
            return true;
        }


        /**public bool CheckLogOnStatus(string userId)
        {
            try
            {
                var db = new ETLDataEntities();
                bool result = false;
                DateTime startTime = DateTime.Today;

                var listTime = from s in db.project_times
                               where s.time_start > startTime && s.time_user_id == userId && s.time_finish == null
                               select s;
                if(listTime != null && listTime.Count() > 0)
                {
                    var first = listTime.First();
                    if(first != null)
                    {
                        if(first.time_other != null && !first.time_other.Equals("Program load") && !first.time_other.Equals("Arrived at DSE"))
                        {
                            result = true;
                        }
                    }
                }
                return result;

            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return false;
            }

        }**/

        public bool CheckLogOnStatus(string userId)
        {
            try
            {
                var db = new ETLDataEntities();
                bool result = false;
                DateTime startTime = DateTime.Today;

                var listTime = from s in db.ETL_ACTUAL_RESOURCE_USAGES
                               join r in db.RESOURCE_INSTANCES on s.GEN_RESOURCE_ID equals r.GEN_RESOURCE_ID
                               where s.START_DATE > startTime && r.RESOURCE_NAME == userId && s.END_DATE == null
                               select s;
                if (listTime != null && listTime.Count() > 0)
                {
                    var first = listTime.First();
                    if (first != null)
                    {
                        //if (first.time_other != null && !first.time_other.Equals("Program load") && !first.time_other.Equals("Arrived at DSE"))
                        //{
                        //    result = true;
                        //}
                    }
                }
                return result;

            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return false;
            }

        }


    }
}
